/**
 * Created by XianTao on 2016/11/10
 * <p/>
 * Copyright (c) 2015-2015
 * Apache License
 * Version 2.0, January 2004
 * http://www.apache.org/licenses/
 */
package org.lego.wechat.base.api;

import org.lego.handle.exception.ExtraInvalidParameterException;
import org.lego.util.ApiResult;
import org.lego.util.DateTimeUtil;
import org.lego.util.HttpUtil;
import org.lego.wechat.base.entity.WxAccessToken;
import org.lego.wechat.base.service.WxAccessTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * 获取access_token
 * <p/>
 * access_token的存储至少要保留512个字符空间。access_token的有效期目前为2个小时，需定时刷新，重复获取将导致上次获取的access_token失效
 */
@Component
public class AccessTokenApi {
    private String url = "https://api.weixin.qq.com/cgi-bin/token";
    private String qyUrl = "";

    @Autowired
    private WxAccessTokenService wxAccessTokenService;

    public WxAccessToken getWxAccessToken(String corpId, Integer agentId, String corpSecret) {
        WxAccessToken current = wxAccessTokenService.findOneByCorpIdAndAgentId(corpId, agentId);
        if (!ObjectUtils.isEmpty(current) && !ObjectUtils.isEmpty(current.getExpiredTime())
                && current.getExpiredTime() > DateTimeUtil.getCurrentTimeSeconds()) {
            return current;
        }
        return refreshWxAccessToken(corpId, agentId, corpSecret, current);
    }

    private synchronized WxAccessToken refreshWxAccessToken(String corpId, Integer agentId, String corpSecret, WxAccessToken wxAccessToken) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("grant_type", "client_credential");
        params.put("appid", corpId);
        params.put("secret", corpSecret);
        ApiResult apiResult = ApiResult.create(HttpUtil.get(url, params));
        if (!apiResult.isSucceed()) {
            throw new ExtraInvalidParameterException("WechatSystem.api.errorCode", String.valueOf(apiResult.getErrorCode()));
        }
        if (ObjectUtils.isEmpty(wxAccessToken)) {
            wxAccessToken = new WxAccessToken();
            wxAccessToken.setCorpId(corpId);
            wxAccessToken.setAgentId(agentId);
        }
        wxAccessToken.setAccessToken(apiResult.getStr("access_token"));
        // -120表示将过期时间提前2分钟 (微信服务器对过期的token，5分钟内仍有效，这样更保证token可用)
        wxAccessToken.setExpiredTime(DateTimeUtil.getCurrentTimeSeconds() + (apiResult.getInt("expires_in") - 120));
        wxAccessTokenService.saveAndFlush(wxAccessToken);
        return wxAccessToken;
    }
}
